package com.wf.security;

import com.wf.common.util.StringUtil;
import com.wf.entity.Menu;
import com.wf.entity.Power;
import com.wf.entity.Role;
import com.wf.entity.User;
import com.wf.provider.MenuProvider;
import com.wf.provider.PowerProvider;
import com.wf.provider.RoleProvider;
import com.wf.provider.UserProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by yuzhongbo on 2017/6/18.
 */
@Service
public class CustomUserService implements UserDetailsService {

    @Autowired
    UserProvider userProvider;
    @Autowired
    RoleProvider roleProvider;
    @Autowired
    PowerProvider powerProvider;
    @Autowired
    MenuProvider menuProvider;

    @Override
    public UserDetails loadUserByUsername(String username) { //重写loadUserByUsername 方法获得 userdetails 类型用户
        User user = new User();
        user.setName(username);
        user = userProvider.selectOne(user);
        if (user != null) {
            List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
            //菜单权限
            List<Role> roles = roleProvider.getRolesByUserId(user.getId());
            for (Role role : roles) {
                if (role != null && !StringUtil.empty(role.getRoleName())) {
                    GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(role.getRoleName());
                    grantedAuthorities.add(grantedAuthority);
                }
            }
            //按钮权限
            List<Power> powers=powerProvider.getPowersByUserId(user.getId());
            Set<String> buttons=new HashSet<>();
            for (Power power : powers) {
                {
                    if (power != null && !StringUtil.empty(power.getButtons())) {
                        String [] bts=power.getButtons().split(",");
                        for (String bt:bts) {
                            buttons.add(bt);
                        }

                    }
                }
            }
            for (String button:buttons) {
                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(button);
                grantedAuthorities.add(grantedAuthority);
            }
            return new MyUserDetails(user.getId(),user.getName(), user.getPassword(),true,grantedAuthorities);
        } else {
            throw new UsernameNotFoundException("admin: " + username + " do not exist!");
        }
    }
}
